/*
 * 文 件 名 : HomeActivity.java
 * 版    权 : China Machi.Co.,Ltd.Copyright 2009-2011.All rights reserved
 * 描    述 : <描述>
 * 修 改 人 : lixg
 * 修改时间 : 2012-8-4
 * 跟踪单号 : <跟踪单号>
 * 修改单号 : <修改单号>
 * 修改内容 : <修改内容>
 */
package com.fire8.dolphin.ui.diary;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.fire8.dolphin.common.Constants;
import com.fire8.dolphin.db.QuestionDAO;
import com.fire8.dolphin.model.Question;
import com.fire8.dolphin.ui.AnswerActivity;
import com.fire8.dolphin.ui.DolphinApplication;
import com.fire8.dolphin.ui.PullDownView;
import com.fire8.dolphin.ui.UserInfoActivity;
import com.fire8.dolphin.ui.PullDownView.OnPullDownListener;
import com.fire8.dolphin.ui.R;
import com.fire8.dolphin.ui.ScrollOverListView;
import com.fire8.dolphin.ui.imgcache.AsynLoad;
import com.fire8.dolphin.ui.more.RegisterActivity;
import com.fire8.dolphin.utils.LogUtil;
import com.fire8.dolphin.utils.StringUtil;
import com.fire8.dolphin.web.RequestUtils;


/**
 * 能量广场
 *
 * @author  lixg
 * @version [版本号,2012-8-4]
 * @see     [相关类/方法]
 * @since   [产品/模块]
 */
public class DiaryListActivity extends ListActivity implements OnItemClickListener
{
    //private static int index=1;
    private final String TAG="dolphin";
    //private QuestionDAO dao;
    private Button btnRight;
    private RadioButton btnButton0;//最新
    private RadioButton btnButton1;//最热
    private RadioButton btnButton2;//我自己的
    private PullDownView pullDownView;
    private ScrollOverListView listView;
    
    private DolphinApplication app;
    private MyAdapter myAdapter;
    
    private AsynLoad asynLoad;
    private String orderby;
    //private List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
    private List<Question> list = new ArrayList<Question>();
    private Map<Integer,View> map;
    private QuestionDAO dao;
    private AnimationDrawable voicePlayAnim;//播放语音时显示的动画
    private int playState=Constants.MEDIA_STATUS_STOP;
    private int playIndex;
    private String playUrl="";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.diary_list);
        //dao = new QuestionDAO(this);
        app = (DolphinApplication)getApplication();
        dao = new QuestionDAO(this);
        orderby = app.getOrderBy();
        getElement();
        setElementEvent();
        //异步加载头像
        asynLoad = new AsynLoad();
        myAdapter = new MyAdapter(this);
        listView.setAdapter(myAdapter);
        new GetDataTask().execute(Question.QUERY_UP);
        //findQuestionList();
        // list需要刷新时调用
        pullDownView.setOnPullDownListener(new OnPullDownListener() {
            
            @Override
            public void onRefresh() {
                LogUtil.d("向下滑");
                new GetDataTask().execute(Question.QUERY_UP);
            }
            
            @Override
            public void onLoadMore() {
                LogUtil.d("向上滑");
                new GetDataTask().execute(Question.QUERY_DOWN);
            }
        });
        //启动语音服务
        startPlayService();
        registerReceiver(this.receiver, new IntentFilter(Constants.VOICE_PLAY_CALLBACK));
    }
    
    private void getElement()
    {
        btnButton0 = (RadioButton)findViewById(R.id.radio_button0);
        btnButton1 = (RadioButton)findViewById(R.id.radio_button1);
        btnButton2 = (RadioButton)findViewById(R.id.radio_button2);
        btnRight = (Button)findViewById(R.id.title_bt_right);
        //listView = (ListView)findViewById(R.id.question_list);
        pullDownView = (PullDownView) findViewById(R.id.pulldownview);
        pullDownView.enableAutoFetchMore(true, 0);
        listView = pullDownView.getListView();
        listView.setDivider(this.getResources().getDrawable(R.color.list_bg));
        listView.setDividerHeight(10);
    }
    
    private void setElementEvent()
    {
        btnRight.setOnClickListener(new OnButtonListener());
        listView.setOnItemClickListener(this);
        btnButton0.setOnClickListener(new RadioButtonListener());
        btnButton1.setOnClickListener(new RadioButtonListener());
        btnButton2.setOnClickListener(new RadioButtonListener());
    }
    
    class OnButtonListener implements OnClickListener
    {

        @Override
        public void onClick(View v)
        {
            //检查是否有注册或登录，如果没有，则不能提交
            if(StringUtil.isEmpty(app.getAccount()))
            {
              //未登录，显示提示信息
                //Toast.makeText(UserInfoActivity.this, "注册或登录后才可以发消息", Toast.LENGTH_LONG).show();
                AlertDialog alert = new AlertDialog.Builder(DiaryListActivity.this)   
                .setTitle("温馨提示")   
                .setIcon(R.drawable.logo_n)   
                .setMessage("需要注册或登录才可以发布消息，现在需要注册吗？")   
                .setPositiveButton("再在注册",   
                        new DialogInterface.OnClickListener() {   
                            public void onClick(DialogInterface dialog,   
                                    int which) {   
                                //跳转到注册页面
                                Intent intent = new Intent(DiaryListActivity.this,RegisterActivity.class);
                                startActivity(intent);
                                //DiaryListActivity.this.finish();
                                return;
                            }   
                        })   
                .setNegativeButton("稍候再说",   
                        new DialogInterface.OnClickListener() {   
                            public void onClick(DialogInterface dialog,   
                                    int which) {   
                                dialog.cancel();   
                                return;
                            }   
                        }).show();  
                return;
            }
            Intent intent = new Intent(DiaryListActivity.this,QuestionAddActivity.class);
            startActivity(intent);
        }
        
    }
    class RadioButtonListener implements OnClickListener
    {

        @Override
        public void onClick(View v)
        {
            if(v.getId() == btnButton0.getId())
            {
                //最新
                orderby="1";
                list.clear();
                new GetDataTask().execute(Question.QUERY_UP);
            }else if(v.getId() == btnButton1.getId())
            {
                //最热
                orderby="3";
                list.clear();
                new GetDataTask().execute(Question.QUERY_UP);
            }else
            {
                //我自己的
                findQuestionList();
            }
        }
        
    }
    /**
     * 从本地库中查询问题列表
     * <功能详细描述> [参数说明]
     *
     * @author lixg
     * @see [类、类#方法、类#成员]
     */
    private void findQuestionList()
    {
        
        DolphinApplication app = (DolphinApplication)getApplication();
        Question question = new Question();
        //question.setUserId(app.getUserId()==""?"0":app.getUserId());
        list = dao.findList(question,Question.QUERY_UP,app.PAGE_SIZE,"1");
        myAdapter.notifyDataSetChanged();
//        pullDownView.notifyDidDataLoad(false);
//        Log.i(TAG,"问题条数: "+list.size());
        //new GetDataTask().execute(Question.QUERY_UP);
    }
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id)
    {
        if(list.isEmpty())return;
        Log.d(TAG,"问题条数: "+list.size());
        Log.d(TAG,"position: "+position);
        if(position >= list.size())return;

        Intent intent = new Intent(this,AnswerActivity.class);
        intent.putExtra("question", list.get(position));
        startActivity(intent);
    }
    
    public final class ViewHolder
    {
        public TextView tvTitle;
        public TextView tvContext;
        public TextView tvAnswerNum;
        public TextView tvDate;
        public TextView tvUserName;
        public TextView tvTimeLong;
        public ImageView imgHead;
        public ImageView imgVoice;
        public ImageView imgContext;
        public ImageView imgContextBg;
    }
    public class MyAdapter extends BaseAdapter
    {
        private LayoutInflater mInflater; 
        
        public MyAdapter(Context context)
        {
            this.mInflater = LayoutInflater.from(context); 
            map = new HashMap<Integer, View>();
        }
        
        public int getCount()
        {
            return list.size();
        }

        
        public Object getItem(int position)
        {
            return list.get(position);
        }

        
        public long getItemId(int position)
        {
            return 0;
        }

        
        public View getView(final int position, View convertView, ViewGroup parent)
        {
            View rowView = map.get(position);
            ViewHolder holder = null; 
            if (rowView == null)
            {
                holder = new ViewHolder();
                rowView = mInflater.inflate(R.layout.question_item, null);
                holder.tvTitle = (TextView)rowView.findViewById(R.id.tv_title);
                holder.tvContext = (TextView)rowView.findViewById(R.id.tv_context);
                holder.tvAnswerNum = (TextView)rowView.findViewById(R.id.tv_answer_num);
                holder.tvDate = (TextView)rowView.findViewById(R.id.tv_date);
                holder.tvUserName = (TextView)rowView.findViewById(R.id.tv_user_name);
                holder.tvTimeLong = (TextView)rowView.findViewById(R.id.tv_time_long);
                
                holder.imgHead = (ImageView)rowView.findViewById(R.id.img_head);
                holder.imgVoice = (ImageView)rowView.findViewById(R.id.img_voice);
                holder.imgContext = (ImageView)rowView.findViewById(R.id.img_context);
                holder.imgContextBg = (ImageView)rowView.findViewById(R.id.img_context_bg);
                //convertView.setTag(holder);
                rowView.setTag(holder);
                map.put(position, rowView);
            }
            else
            {
                holder = (ViewHolder)rowView.getTag();
            }

            
            final Question question = (Question)getItem(position);
            LogUtil.d("title:"+question.getTitle());
            holder.tvTitle.setText(question.getTitle());
            String txt = question.getContext();
            if(txt.length() >10)
            {
                txt = txt.substring(0, 10);
            }
            holder.tvContext.setText(txt);//显示标题 
            holder.tvAnswerNum.setText("回复:"+question.getAnswerNum());
            holder.tvDate.setText(question.getUpdateDate());
            String userName = question.getUserName();
            holder.tvUserName.setText(userName==null?"未知":userName);
            
            LogUtil.d("picture = "+question.getPicture());
            try
            {
                if(!StringUtil.isEmpty(question.getPicture()))
                {
                    if(question.getPicture().contains("http"))
                    {
                        asynLoad.showimgAnsy(holder.imgContext,question.getPicture());
                    }else
                    {
                        Options opt = new BitmapFactory.Options();
                        opt.inSampleSize = 4;
                        Bitmap bmp = BitmapFactory.decodeFile(question.getPicture(),opt);
                        holder.imgContext.setImageBitmap(bmp);
                    }
                    
                    holder.imgContext.setVisibility(View.VISIBLE);
                    holder.imgContextBg.setVisibility(View.VISIBLE);
                }
                asynLoad.showimgAnsy(holder.imgHead,RequestUtils.IMG_URL+question.getUserId()+".jpg");
            }
            catch (Exception e)
            {
                LogUtil.e("",e);
            }
            
            
            
            //anseylodar.showimgAnsy(holder.imgHead,RequestUtils.IMG_URL+question.getUserId()+".jpg");//异步加载图片
            if(!StringUtil.isEmpty(question.getVoice()))
            {
                holder.tvTimeLong.setText(question.getVoiceLong()+"\"");
                holder.imgVoice.setBackgroundResource(R.anim.voice_play_gray);
                holder.tvTimeLong.setVisibility(View.VISIBLE);
                holder.imgVoice.setVisibility(View.VISIBLE);
                holder.imgVoice.setOnClickListener(new OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        //点击播放录音
                        if(!StringUtil.isEmpty(question.getVoice()))
                        {
                            onBtnVoiceClick(position, question, v);
                        }
                    }
                    
                });
            }
            
            return rowView;
        }
        
    }
    /**
     * 点击播放图标时
     * <功能详细描述>
     * @param position
     * @param question
     * @param v [参数说明]
     *
     * @author lixg
     * @see [类、类#方法、类#成员]
     */
    private void onBtnVoiceClick(final int position,
            final Question question, View v)
    {
        if(playState == Constants.MEDIA_STATUS_PLAYING && playUrl.equals(question.getVoice()))
        {
            //停止播放
            LogUtil.d("暂停播放:"+playUrl);
            sendMessage(Constants.MEDIA_PAUSE,"");
            //停止动画
            if (voicePlayAnim != null)
            {
                voicePlayAnim.setOneShot(true);
                voicePlayAnim.stop();
            }
        }else if(playState == Constants.MEDIA_STATUS_PAUSE && playUrl.equals(question.getVoice()))
        {
            voicePlayAnim.setOneShot(false);
            voicePlayAnim.start();
            sendMessage(Constants.MEDIA_START,"");
        }
        else
        {
            if (voicePlayAnim != null)
            {
                voicePlayAnim.setOneShot(true);
                voicePlayAnim.stop();
            }
            playUrl = question.getVoice();
            playIndex = position;
            LogUtil.d("开始播放:"+playUrl);
            sendMessage(Constants.MEDIA_INIT,playUrl);
            //启动动画
            voicePlayAnim = (AnimationDrawable)v.getBackground();
            voicePlayAnim.setOneShot(false);
            voicePlayAnim.start();
        }
    }
    
    private class GetDataTask extends AsyncTask<Integer, Void, String> {

        @Override
        protected String doInBackground(Integer... params) {
            // 在这里可以做一些后台工作
            if(!RequestUtils.getInstall().isConnect(DiaryListActivity.this))
            {
                return "网络不可用";
            }
            int opt = params[0];
            //LogUtil.d("这是第"+index+"次取数据");
            //index++;
            if(Question.QUERY_UP == opt)
            {
                //向上刷新
                return refreshData();
            }else
            {
                //向下加载更多
                return loadMoreData();
            }
            
        }

        @Override
        protected void onPostExecute(String result) {
            // 下拉后增加的内容
            //mListItems.addFirst("Added after refresh...");
            
            LogUtil.d("list长度："+list.size());
            Toast.makeText(DiaryListActivity.this, result, Toast.LENGTH_LONG).show();
            
            myAdapter.notifyDataSetChanged();
            //pullDownView.notifyDidRefresh(list.isEmpty());
            pullDownView.notifyDidDataLoad(false);
            //getListView().setAdapter(new MyAdapter(HomeActivity.this));
            super.onPostExecute(result);
        }
    }
    
    //向上刷新数据
    private String refreshData()
    {
        //LogUtil.d("请求远程数据时，remoteId:"+remoteId);
        //向上刷，按排序规则取最上面的数据，将原来的数据清空
        List<Question> questions = RequestUtils.getInstall().getQuestionList(0, Question.QUERY_UP, null,orderby);
        if(questions != null && !questions.isEmpty())
        {
            list.clear();
            map.clear();
            list.addAll(questions);
        }
        
        return "数据已更新";
    }
    
    //向下加载更多
    private String loadMoreData()
    {
        //取查询条件
        List<Question> questions = RequestUtils.getInstall().getQuestionList(list.size(), Question.QUERY_DOWN, null,orderby);
        if(!questions.isEmpty())
        {
            list.addAll(questions);
        }else
        {
            return "亲，你的数据是最新的了";
        }
        return "刷新完成";
    }
    
    /**发送控制指令播或停止语音**/
    private void sendMessage(int command,String param)
    {
        Intent intent = new Intent(Constants.VOICE_PLAY_CONTROL);
        Bundle bundle = new Bundle();
        bundle.putInt("command", command);
        bundle.putString("param", param);
        intent.putExtras(bundle);
        sendBroadcast(intent);
    }
    
    /**启动语音播放服务**/
    private void startPlayService()
    {
        LogUtil.d("startPlayService");
        Intent intent = new Intent();
        intent.setAction("com.fire8.dolphin.service.voicePlayService");
        startService(intent);
    }
    /**定义广播接收器**/
    private BroadcastReceiver receiver= new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context arg0, Intent intent)
        {
            int commend = intent.getIntExtra("command", 0);
            switch (commend)
            {
                case Constants.MEDIA_INIT:
                    //初始化完成,已经开始播放，修改播放状态
                    playState = Constants.MEDIA_STATUS_PLAYING;
                    LogUtil.d("修改播放状态为："+playState);
                    break;
                case Constants.MEDIA_START:
                    playState = Constants.MEDIA_STATUS_PLAYING;
                    break;
                case Constants.MEDIA_PAUSE:
                    playState = Constants.MEDIA_STATUS_PAUSE;
                    if (voicePlayAnim != null)
                    {
                        voicePlayAnim.setOneShot(true);
                        voicePlayAnim.stop();
                    }
                    break;
                case Constants.MEDIA_STATUS_STOP:
                    //播放完成，修改播放状态
                    playState = Constants.MEDIA_STATUS_STOP;
                    LogUtil.d("修改播放状态为："+playState);
                    if (voicePlayAnim != null)
                    {
                        voicePlayAnim.setOneShot(true);
                        voicePlayAnim.stop();
                    }
                    break;
                default:
                    break;
            }
        }
        
    };

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
    
}
